package com.wanghua.mall.user.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign在远程调用时会创建一个新的request，会丢失请求头信息，RequestInterceptor可解决
 *
 * @author wanghua
 * @create 2021-09-08 13:41
 */
@Configuration
public class UserFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            //1.RequestContextHolder拿到刚进来的请求数据
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
            if (servletRequestAttributes != null) {
                HttpServletRequest request = servletRequestAttributes.getRequest();//老的请求
                //2.同步请求头数据->Cookie
                if (request != null) {
                    String cookie = request.getHeader("Cookie");
                    template.header("Cookie", cookie);
                }
            }
        };

    }
}
